package pers.gxm.memento.execution;

import pers.gxm.memento.Gamer;
import pers.gxm.memento.Memento;

import java.io.*;

public class Main {
    public static void main(String[] args) {
        File file = new File("game.dat");
        Gamer gamer = new Gamer(100);
        Memento memento;
        if(file.exists()){
//            存档存在
            try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
                memento = (Memento) ois.readObject();
                gamer.restoreMemento(memento);

            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }else{
             memento = gamer.createMemento();
        }
        
        for(int i = 0;i < 100 ;i++){
            System.out.println("========== " + i);
            System.out.println("当前状态：" +  gamer);
            gamer.bet();
            int money = gamer.getMoney();
            System.out.println("所持金钱为" + money + "元。");

            if(money >= 2 * memento.getMoney()){
                try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
                    oos.writeObject(memento);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }else if(money > memento.getMoney()){
                System.out.println("当前金钱总量增加");
            }else if(money < memento.getMoney() / 2){
                System.out.println("当前金额减少很多，游戏恢复至上次状态。");
                gamer.restoreMemento(memento);
            }
        }
//        Memento memento1 = new Memento();访问权限不足

    }
}
